/*
 * @Author: 梁卓
 * @Date: 2022-01-28 21:45:59
 * @LastEditTime: 2022-03-03 16:59:29
 * @LastEditors: Please set LastEditors
 * @Description: 路由
 * @FilePath: \dreamUi\src\router\index.js
 */
import Vue from "vue";
import VueRouter from "vue-router";
/** 引入vuex */
import store from '@/store/index';
/** 引入axios */
import ajax from '@/utils/ajax';
/** 引入views */
import Login from '@/views/Login';
import Home from '@/views/Home';
import { formatMenus } from '@/utils/initMenus'
import honorScore from '@/componets/echarts/HonorScore'
import studyScore from '@/componets/echarts/StudyScore'


Vue.use(VueRouter);

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/home',
    name: 'home',
    meta: {title: '首页', noCache: true},
    component: Home,
    children:[]
  },
  {
    path: '/honorScore',
    component: honorScore
  },
  {
    path: '/studyScore',
    component: studyScore
  }
];


const router = new VueRouter({
  routes,
});

/**
 * 路由导航
 * to: 将要去的页面
 * from；从哪个页面过来
 * next: 到那个页面
 */
router.beforeEach((to,from,next) => {
  // console.log('router', router)
  // 判读用户是否已经登录
  const token = sessionStorage.getItem('token');
  if (! token) {
    if (to.path === '/login') {
      next()
    } else {
      next(`/login ? redirect = ${to.fullPath}`);
    }
  } else {
      // 向后端发送请求，获取用户基本信息
      ajax.get('/user/getInfo').then((res) => {

        const user = res.data.data;
        store.commit('setName', user.username);
        store.commit('setAvatar', user.avatar);
        if (user.roles.length > 0) {
          // 添加角色、菜单、权限等信息
          store.commit('setRoles',user.roles);
          // 格式化菜单
          const menuList = formatMenus(user.menus);
          menuList.forEach((item,index,array) => {
            router.addRoute(item);
          });
          // router.addRoute(menuList[0]);
          store.commit('setMenus',menuList);
          store.commit('setPermissions',user.permissions);
        }
      }, (err) => {
        
      })
    // 已经登录
    if (to.path === '/login') {
      next('/');
    } else {
      next();
    }
    
  }
})

export default router;
